package com.yh.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yh.entity.Zhanfeng;

/**
 * 
 * <pre>
 * - 权限过滤器
 * ClassName : com.yh.filter.AuthFilter
 * &#64;author 湛锋
 * Date : 2020年8月6日 下午7:31:59
 * </pre>
 *
 */
//@WebFilter(value = "/*",dispatcherTypes=DispatcherType.REQUEST)//默认
//@WebFilter(value = "/*",dispatcherTypes = DispatcherType.FORWARD)//请求转发拦截
//@WebFilter("/*")
public class AuthFilter implements Filter {

	/**
	 * - 需要进行权限判断的路径
	 */
	public List<String> authList = new ArrayList<String>();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Collections.addAll(authList, "admin", "author", "user");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		String path = req.getRequestURI();
		path = path.substring(req.getContextPath().length() + 1);

		int index = path.indexOf("/");
		if (index == -1) {// 访问的是首页(欢迎页)
			chain.doFilter(request, response);
		} else {
			path = path.substring(0, index);// 得到需要判断的路径
			if (authList.contains(path)) {// 需要判断则进行判断
				Zhanfeng user = (Zhanfeng) req.getSession().getAttribute("user");
				if (user == null) {// session中没有user，则是没有登录。跳转到登录界面
					resp.sendRedirect(req.getContextPath() + "/login.jsp");
				} else {
					if(user.getZfName().equals("admin")) {
						chain.doFilter(request, response);
					}else if (user.getZfName().equals("author")&&path.equals("author")) {
						chain.doFilter(request, response);
					}else if (user.getZfName().equals("user")) {
						chain.doFilter(request, response);
					}else {
						resp.sendError(403, "您无权访问");
					}
				}
			} else {// 不需要判断的路径直接进入
				chain.doFilter(request, response);
			}
		}
	}

	@Override
	public void destroy() {
		
	}

}
